package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.constance.ScheduleConstants;
import com.heima.model.schedule.dots.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskInfoLogsMapper;
import com.heima.schedule.mapper.TaskInfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StopWatch;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
@Transactional
@Slf4j
public class TaskImpl implements TaskService {


    @Override
    public long addTask(Task task) {
        //添加任务到数据库
        boolean success = addTaskToDb(task);
        //任务添加至redis
        if (success) {
            addTaskToRedis(task);
        }
        return task.getTaskId();
    }

    @Override
    public boolean cancelTask(Long taskId) {

        boolean ok = false;
        //删除任务表中的任务 更新日志状态
        Task task = deleteAndUpdateLogs(taskId, ScheduleConstants.CANCELLED);
        if (task != null) {
            //从redis中删除
            deleteFromRedis(task);
            ok = true;
        }
        return ok;
    }

    @Override
    public Task pullTask(Integer type, Integer priority) {
        Task task = null;

        try {
            //从chache中的list中拉取数据
            String key = type + "_" + priority;
            String objStr = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
            if (StringUtils.isNotBlank(objStr)) {
                task = JSON.parseObject(objStr, Task.class);
                //修改数据库数据
                deleteAndUpdateLogs(task.getTaskId(), ScheduleConstants.EXECUTED);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.warn("cosumer pull task error task id  : {}", task.getTaskId());
        }

        return task;
    }

    @Override
    @Scheduled(cron = "0 */1 * * * ?") //每分钟执行一次 要使用定时任务需要在启动类开启注解
    public void syncZset2List() {
        //获得分布式锁
        String token = cacheService.tryLock("SCHEDULE_TASK", 1000 * 30);
        if (StringUtils.isNotBlank(token)) {
            log.info("刷新redis定时任务启动.....");
            //拿到所有未来要执行的队列
            Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
            for (String futureKey : futureKeys) {
                //按照key和分值（执行时间） 找到即将要执行的任务  就是执行时间小于当前时间的任务
                Set<String> tasks = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());
                if (!tasks.isEmpty()) {
                    //通过管道把这些任务放到topic（即时任务队列中）
                    String type_priority = futureKey.split(ScheduleConstants.FUTURE)[1];
                    cacheService.refreshWithPipeline(futureKey, ScheduleConstants.TOPIC + type_priority, tasks);
                    log.info("成功将{}刷新到{}", futureKey, ScheduleConstants.TOPIC + type_priority);
                }

            }
        }
    }

    /**
     * 从redis中删除数据
     *
     * @param task
     */
    private void deleteFromRedis(Task task) {
        if (task != null) {
            String key = task.getTaskType() + "_" + task.getPriority();
            if (task.getExecuteTime() <= System.currentTimeMillis()) {
                //从list队列中删除
                cacheService.lRemove(ScheduleConstants.TOPIC + key, 0, JSON.toJSONString(task));
            } else {
                //从zset队列中删除
                cacheService.zRemove(ScheduleConstants.FUTURE, JSON.toJSONString(task));
            }

            log.warn("delele  task from redis success , task id : {}", task.getTaskId());
        }
    }

    /**
     * 从数据库删除task，更新日志表
     *
     * @param taskId
     * @param cancelled
     * @return
     */
    private Task deleteAndUpdateLogs(Long taskId, int cancelled) {
        Task task = new Task();

        try {
            //删除任务
            taskInfoMapper.deleteById(taskId);
            //更新日志数据
            TaskinfoLogs taskinfoLogs = taskInfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(cancelled);
            taskInfoLogsMapper.updateById(taskinfoLogs);
            BeanUtils.copyProperties(taskinfoLogs, task);
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        } catch (BeansException e) {
            log.error("cancel task execption task id is : {}", taskId);
        }

        return task;

    }


    /**
     * 添加任务到redis
     *
     * @param task
     */

    @Autowired
    private CacheService cacheService;

    private void addTaskToRedis(Task task) {
        //任务执行时间小于等于当前时间添加到list集合
        String key = task.getTaskType() + "_" + task.getPriority();

        //获取五分钟后的毫秒值
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        long afterFiveMin = calendar.getTimeInMillis();

        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            cacheService.lLeftPush(ScheduleConstants.TOPIC + key, JSON.toJSONString(task));
        } else if (task.getTaskType() <= afterFiveMin) {
            //如果任务执行时间在5分钟内 就添加到redis的zset中
            cacheService.zAdd(ScheduleConstants.FUTURE + key, JSON.toJSONString(task), task.getExecuteTime());
        }
        //如果任务的执行时间在五分钟以后，就只是放在了 mysql中，通过定时任务得到了。

    }

    @Autowired
    private TaskInfoMapper taskInfoMapper;

    @Autowired
    private TaskInfoLogsMapper taskInfoLogsMapper;

    private boolean addTaskToDb(Task task) {
        boolean success = false;
        try {
            //添加到任务表
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task, taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskInfoMapper.insert(taskinfo);
            //插入数据库后自动得到id
            task.setTaskId(taskinfo.getTaskId());
            //添加到任务日志表
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(task, taskinfoLogs);
            taskinfoLogs.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED); //初始化状态
            taskinfoLogs.setVersion(1);
            taskInfoLogsMapper.insert(taskinfoLogs);
            success = true;
        } catch (BeansException e) {
            e.printStackTrace();
        }

        return success;

    }


    /**
     * 数据库任务定时同步到redis
     */
    @PostConstruct  //表示这个是一个初始化方法 ，当微服务挂掉之后重启的时候，执行这个任务
    @Scheduled(cron = "0 */5 * * * ?") //每五分钟执行一次
    public void reloadDb2Cache(){
        //删除缓存中的数据
        clearCacheTasks();
        //查询复合条件的任务，小于未来五分钟的任务
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        List<Taskinfo> taskinfos = taskInfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().lt(Taskinfo::getExecuteTime, calendar.getTime()));
        //任务添加到cache
        if (taskinfos != null && taskinfos.size() > 0){
            for (Taskinfo taskinfo : taskinfos) {
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo, task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                addTaskToRedis(task);
            }
        }

        log.info("数据库中的任务同步到redis");
    }


    /**
     * 清除缓存中的任务数据
     */
    private void clearCacheTasks() {
        //查询所有和延时任务相关的key 即时任务，延时任务
        Set<String> futureTasks = cacheService.scan(ScheduleConstants.FUTURE + "*");
        Set<String> topicTasks = cacheService.scan(ScheduleConstants.TOPIC + "*");
        cacheService.delete(futureTasks);
        cacheService.delete(topicTasks);
    }


}
